//
//  CMMidiController.m
//  Perilla
//
//  Created by Martin Schiøth Dyrby on 23/11/12.
//  Copyright (c) 2012 Martin Schiøth Dyrby. All rights reserved.
//

#import "CMMidiController.h"
#include "RtMidi.h"

@implementation CMMidiController

RtMidiIn *midiin = 0;

- (id) init{
    
	try {
		midiin = new RtMidiIn();
        
		midiin->openPort( 0 );
        
		midiin->ignoreTypes( false, false, false );
        
		unsigned int nPorts = midiin->getPortCount();
        
		std::string portName;
		for ( unsigned int i=0; i<nPorts; i++ ) {
			try {
				portName = midiin->getPortName(i);
			}
			catch ( RtError &error ) {
				error.printMessage();
			}
		}
	} catch (RtError &error) {
		error.printMessage();
	}
    
	if(midiin) {
		[NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(checkMidiIn:) userInfo:nil repeats:YES];
	}

    return self;
}

- (void)checkMidiIn:(NSTimer *) timer {
    
	std::vector<unsigned char> message;
	midiin->getMessage( &message );
    
	if ( message.size() > 0) {
        NSLog(@"size %ld, message %d, %d, %d", message.size(), message[0], message[1], message[2]);
        
		NSNumber* type = [NSNumber numberWithInt: message[0]];
		NSNumber* num = [NSNumber numberWithInt: message[1]];
		NSNumber* value = [NSNumber numberWithInt: message[2]];
        
        NSDictionary* dict = [[NSDictionary alloc] initWithObjectsAndKeys: type, @"type", num, @"num", value, @"value", nil];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"midiMessageReceived" object:dict];        
	}
}

@end
